package com.SFA.OrderManagement;

import java.util.ArrayList;
import java.util.List;

import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ByteArrayEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.util.EntityUtils;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.content.ContentValues;
import android.content.Context;
import android.content.SharedPreferences;
import android.database.sqlite.SQLiteCursor;
import android.database.sqlite.SQLiteDatabase;
import android.text.TextUtils;

import com.FrameWork.Common.MyApplication;
import com.FrameWork.DB.DataProvider;
import com.FrameWork.Entity.GlobalInfo;
import com.FrameWork.Entity.OrderEntity;
import com.FrameWork.Entity.OrderLine;
import com.FrameWork.Entity.PaymentEntity;
import com.FrameWork.Entity.ProductEntity;
import com.FrameWork.Utils.DateTimeUtils;
import com.FrameWork.Utils.Utils;
import com.umeng.analytics.MobclickAgent;

public class OrderManager {

	//根据订单号，联系人，联系电话，地址等条件查询
	public List<OrderEntity> QueryOrder(Context context,String keyword, int PageSize,int PageIndex)
	{

		List<OrderEntity> list = new ArrayList<OrderEntity>();
		DataProvider provider = MyApplication.getInstance().DataProvider;


		String SQL ="SELECT T1.ID,ORDER_NO,ORDER_DATE,REQ_DELIVERY_DATE,CUSTOMER_ID,TOTAL_AMOUNT,TOTAL_QUANTITY,STATUS," +
				"VISIT_ID,ORDERTYPE,CONFIRMED_DATE,TRUCK_CODE,ADDITIONAL_INFO,t2.NAME,DISC_AMOUNT,E.DELIVERY_ADDRESS,E.CONTACT_LINK,E.CONTACT_MAN,EXTENDED_AMOUNT,DELIVERY_TYPE " +
				" FROM ORDER_HEADERS T1 INNER JOIN CUSTOMERS T2 ON T1.CUSTOMER_ID=T2.ID  INNER JOIN ORDER_ENTEND E on E.ID=T1.ID  ";
		if(!TextUtils.isEmpty(keyword))
			SQL +=" WHERE ORDER_NO LIKE  \'%" +keyword+ "%\'  OR CONTACT_LINK  LIKE  \'%" +keyword+ "%\' OR CONTACT_MAN LIKE  \'%" +keyword+ "%\' OR DELIVERY_ADDRESS  LIKE   \'%" +keyword+ "%\'  " ;
		SQL += " ORDER BY ORDER_DATE DESC limit " +  PageSize + " offset " + PageIndex*PageSize;
		SQLiteCursor cursor = null;
		try
		{
			cursor = provider.Query(SQL);
			while(cursor.moveToNext())
			{
				OrderEntity entity = new OrderEntity();
				entity.ID = cursor.getString(0);
				entity.ORDER_NO = cursor.getString(1);
				entity.ORDER_DATE = cursor.getString(2);
				entity.REQ_DELIVERY_DATE= cursor.getString(3);
				entity.CUSTOMER_ID= cursor.getString(4);
				entity.TOTAL_AMOUNT= cursor.getFloat(5) ;
				entity.TOTAL_QUANTITY= cursor.getInt(6);
				entity.STATUS= cursor.getString(7);
				entity.VISIT_ID= cursor.getString(8);
				entity.ORDERTYPE= cursor.getString(9);
				entity.CONFIRMED_DATE= cursor.getString(10);
				entity.TRUCK_CODE= cursor.getString(11);
				entity.ADDITIONAL_INFO= cursor.getString(12);
				entity.NAME = cursor.getString(13);
				entity.DISC_AMOUNT=cursor.getFloat(14);
				entity.DELIVERY_ADDRESS=cursor.getString(15);
				
				entity.CONTACT_LINK=cursor.getString(16);
				entity.CONTACT_MAN=cursor.getString(17);
				if(!cursor.isNull(18))
					entity.EXTENDED_AMOUNT=cursor.getFloat(18);
				if(!cursor.isNull(19))
					entity.DELIVERY_TYPE=cursor.getInt(19);
				list.add(entity);
			}
		}
		catch(Exception err)
		{
			err.printStackTrace();
			MobclickAgent.reportError(context, err.getMessage());
		}
		finally
		{
			if(cursor != null)
			{
				cursor.close();
				cursor = null;
			}
		}
		return list;
	}

	public String GenertorOrderNo(Context context)
	{
		String date =DateTimeUtils.GetCurrentTime();
		date = date.substring(0,8);
		String id = date + "-" + GlobalInfo.GetInstance(context).getEmployeeCode() + "-";
		DataProvider provider = DataProvider.Instance(context);

		SQLiteCursor cursor=null;
		try
		{
			cursor= provider.Query("SELECT count(*) FROM ORDER_HEADERS WHERE ORDER_NO LIKE '" + id + "%'");
			if(cursor.moveToNext())
			{
				id += cursor.getInt(0)+1 + "";
			}
		}
		catch(Exception err)
		{
			return id;
		}
		finally
		{
			if(cursor != null)
			{
				cursor.close();
				cursor = null;
			}

		}
		return id;
	}

	@SuppressWarnings("finally")
	public boolean Save(Context context, OrderEntity entity,boolean temp)
	{

		boolean iserror=false;
		SQLiteDatabase db=MyApplication.getInstance().DataProvider.getWritableDatabase();
		db.beginTransaction();
		try {

			for (int i = 0; i < entity.Lines.size(); i++) {
				ArrayList<ContentValues> arrayValues = new ArrayList<ContentValues>(1);
				ContentValues cvline = new ContentValues();
				OrderLine  line=entity.Lines.get(i);
				if(line.ID==null){
					line.ID=Utils.getId(DateTimeUtils.GetCurrentTime());
				}
				cvline.put("ID", line.ID);
				cvline.put("ORDER_NO", entity.ORDER_NO);
				cvline.put("PRODUCT_ID", line.PRODUCT_ID);
				cvline.put("UOM_CODE", line.Product.UOM_CODE);
				cvline.put("QUANTITY_ORDERED", line.QUANTITY_ORDERED);
				cvline.put("LINE_AMOUNT", line.LINE_AMOUNT);
				cvline.put("Quantity_Received", line.Quantity_Received);
				cvline.put("ARRIVAL_date", line.ARRIVAL_date);
				cvline.put("Confirmed_Date", line.Confirmed_Date);
				cvline.put("OrderLineStatus", line.OrderLineStatus);
				cvline.put("CANCELLED", "N");
				cvline.put("promotion_id", line.promotion_id);
				arrayValues.add(cvline);
				insert2DB(db, "ORDER_LINES", arrayValues);
				if(!temp){
					cvline.put("DIRTY", "1");
					insert2DB(db, "UPLOAD_ORDER_LINES", arrayValues);
				}
				arrayValues.clear();
				cvline.clear();
			}

			ArrayList<ContentValues> arrayValues = new ArrayList<ContentValues>(1);
			ContentValues cv = new ContentValues();
			if (entity.ID == null) {
				entity.ID = Utils.getId(DateTimeUtils.GetCurrentTime());
			}
			cv.put("ID", entity.ID);
			cv.put("ORDER_NO", entity.ORDER_NO);
			cv.put("ORDER_DATE", entity.ORDER_DATE);
			cv.put("REQ_DELIVERY_DATE", entity.REQ_DELIVERY_DATE);
			cv.put("CUSTOMER_ID", entity.CUSTOMER_ID);
			cv.put("TOTAL_AMOUNT", entity.TOTAL_AMOUNT);
			cv.put("TOTAL_QUANTITY",entity.TOTAL_QUANTITY);
			cv.put("DISC_RATE", entity.DISC_RATE);
			cv.put("DISC_AMOUNT", entity.DISC_AMOUNT);
			cv.put("STATUS", entity.STATUS);
			cv.put("VISIT_ID", entity.VISIT_ID);
			cv.put("ORDERTYPE", entity.ORDERTYPE);
			cv.put("CONFIRMED_DATE", entity.CONFIRMED_DATE);
			cv.put("TRUCK_CODE", entity.TRUCK_CODE);
			cv.put("ADDITIONAL_INFO", entity.ADDITIONAL_INFO);
			cv.put("EXTENDED_AMOUNT", entity.EXTENDED_AMOUNT);
			arrayValues.add(cv);
			insert2DB(db, "ORDER_HEADERS", arrayValues);
			if(!temp){
				cv.put("DIRTY", "1");
				insert2DB(db, "UPLOAD_ORDER_HEADERS", arrayValues);
			}
			arrayValues.clear();
			cv.clear();
			cv.put("ID", entity.ID);
			cv.put("CONTACT_MAN", entity.CONTACT_MAN);
			cv.put("CONTACT_LINK", entity.CONTACT_LINK);
			cv.put("DELIVERY_ADDRESS", entity.DELIVERY_ADDRESS);
			cv.put("DELIVERY_TYPE", entity.DELIVERY_TYPE);
			cv.put("ACTIVE", entity.ACTIVE);
			arrayValues.add(cv);
			insert2DB(db, "ORDER_ENTEND", arrayValues);
			if(!temp){
				cv.put("DIRTY", "1");
				insert2DB(db, "UPLOAD_ORDER_ENTEND", arrayValues);
			}
			arrayValues.clear();
			cv.clear();

			for (int i = 0; i < entity.paymentlist.size(); i++) {
				ArrayList<ContentValues> pamentValues = new ArrayList<ContentValues>(1);
				ContentValues cvpay = new ContentValues();
				PaymentEntity  pay=entity.paymentlist.get(i);
				if(pay.ID == null)
					pay.ID=Utils.getId(DateTimeUtils.GetCurrentTime());
				else
					continue;
				if(pay.ORDER_ID==null){
					pay.ORDER_ID=entity.ID;
				}
				cvpay.put("USER_ID", GlobalInfo.GetInstance(context).getUserID());
				cvpay.put("ID", pay.ID);
				cvpay.put("CUSTOMER_ID", pay.CUSTOMER_ID);
				cvpay.put("ORDER_ID", pay.ORDER_ID);
				cvpay.put("PAYMENT_DATE", pay.PAYMENT_DATE);
				cvpay.put("PAYMENT_AMOUNT", pay.PAYMENT_AMOUNT);
				cvpay.put("PAYMENT_TYPE", pay.PAYMENT_TYPE);
				cvpay.put("ACTIVE", "True");
				pamentValues.add(cvpay);
				insert2DB(db,"PAYMENT_RECORD",pamentValues);
				cvpay.put("DIRTY", "1");
				insert2DB(db, "UPLOAD_PAYMENT_RECORD", pamentValues);
			}
			db.setTransactionSuccessful();
			iserror=true;
		} catch (Exception ex) {
			iserror = false;
			MobclickAgent.reportError(context, "数据插入异常：" + ex.toString());
		}finally{
			db.endTransaction();
			return iserror;
		}

	}
	public OrderEntity getOrderEntendById(Context context,OrderEntity entity){
		DataProvider provider = MyApplication.getInstance().DataProvider;
		String sql="select * from ORDER_ENTEND where id=\'%1$s\' ";
		SQLiteCursor cursor=null;
		try {
			sql=String.format(sql, entity.ID);
			cursor = provider.Query(sql);

			if(cursor.moveToFirst()){
				entity.CONTACT_MAN=cursor.getString(cursor.getColumnIndex("CONTACT_MAN"));
				entity.CONTACT_LINK=cursor.getString(cursor.getColumnIndex("CONTACT_LINK"));
				entity.DELIVERY_ADDRESS=cursor.getString(cursor.getColumnIndex("DELIVERY_ADDRESS"));
				entity.DELIVERY_TYPE=cursor.getInt(cursor.getColumnIndex("DELIVERY_TYPE"));
			}
		} catch (Exception err) {
			err.printStackTrace();
			MobclickAgent.reportError(context, err.getMessage());
		}finally{
			if(cursor!=null){
				cursor.close();
				cursor=null;
			}
		}
		return entity;
	}




	private boolean insert2DB(SQLiteDatabase db,String tableName,ArrayList<ContentValues> arrayValues) throws Exception{
		boolean iserror=true;
		for (ContentValues c : arrayValues) {
			long rowId=db.insertWithOnConflict(tableName, null, c, db.CONFLICT_IGNORE);
			long rows=db.updateWithOnConflict(tableName, c, "ID=?", new String[]{c.getAsString("ID")}, db.CONFLICT_IGNORE);
			if(rowId==-1&&rows==0){
				iserror=false;
				throw new Exception("出现插入冲突(Conflict)！返回值rowId为-1。");
			}
		}

		return iserror;
	}
	public boolean updateCancelDB(String orderNo,boolean temp){
		DataProvider provider=MyApplication.getInstance().DataProvider;
		boolean iserror = false;
		SQLiteDatabase db=provider.getWritableDatabase();
		db.beginTransaction();
		try {
			ContentValues cv = new ContentValues();
			cv.put("ORDERLINESTATUS", "1");
			db.update("ORDER_LINES", cv, "ORDER_NO=?", new String[]{orderNo});
			db.update("UPLOAD_ORDER_LINES", cv, "ORDER_NO=?", new String[]{orderNo});
			
			iserror=true;
			db.setTransactionSuccessful();
		} catch (Exception e) {
			iserror=false;
		}finally{
			db.endTransaction();
			return iserror;
		}

	}

	public boolean updatePaymentActive(String userId,boolean temp){
		DataProvider provider=MyApplication.getInstance().DataProvider;
		boolean iserror = false;
		SQLiteDatabase db=provider.getWritableDatabase();
		db.beginTransaction();
		try {
			ContentValues cv = new ContentValues();
			cv.put("ACTIVE", "False");
			int update = db.update("PAYMENT_RECORD", cv, "USER_ID=?", new String[]{userId});
			if(!temp){
				int update1 = db.update("UPLOAD_PAYMENT_RECORD", cv, "USER_ID=?", new String[]{userId});
			}
			iserror=true;
			db.setTransactionSuccessful();
		} catch (Exception e) {
			iserror=false;

		}finally{
			db.endTransaction();
			return iserror;
		}
	}



	public ProductEntity getProductEntityByProductId(Context context,String productId){
		ProductEntity entity=new ProductEntity();
		DataProvider provider = MyApplication.getInstance().DataProvider;
		SQLiteCursor cursor=null;
		//		String sql="select * from products where id=\'%1$s\'";
		String sql="select p.ID,p.CODE,p.DUN_CODE,p.DESCRIPTION,p.SHORT_DESCRIPTION,U.UOM_CODE," +
				"p.FORM_CODE,i.PIECE_PRICE,i.CASE_PRICE,i.FLAG,u.DENOMINATOR " +
				"FROM CUSTOMER_PROD_LIST_ITEMS I INNER JOIN PRODUCTS p ON p.ID=i.PRODUCT_ID " +
				"INNER JOIN PRODUCT_UOMS U WHERE U.PRODUCT_ID=P.ID AND i.ACTIVE=\'True\' AND p.ACTIVE='True' AND p.ID=\'%1$s\'";
		sql=String.format(sql, productId);
		try {
			cursor=provider.Query(sql);
			if (cursor.moveToFirst()) {
				entity.ID=productId;
				entity.UOM_CODE=cursor.getString(cursor.getColumnIndex("UOM_CODE"));
				entity.CODE=cursor.getString(cursor.getColumnIndex("CODE"));
				entity.PIECE_PRICE=cursor.getFloat(cursor.getColumnIndex("PIECE_PRICE"));
				entity.SHORTDESCRIPTION=cursor.getString(cursor.getColumnIndex("SHORT_DESCRIPTION"));
				entity.DESCRIPTION=cursor.getString(cursor.getColumnIndex("DESCRIPTION"));
			}
		} catch (Exception err) {
			err.printStackTrace();
			MobclickAgent.reportError(context, err.getMessage());
		}finally{
			if(cursor!=null){
				cursor.close();
				cursor=null;
			}
		}
		return entity;
	}


	public List<OrderLine> getOrderLineListByOrderNo(Context context,String OrderNo){
		List<OrderLine> list=new ArrayList<OrderLine>();
		SQLiteCursor cursor=null;
		DataProvider provider = MyApplication.getInstance().DataProvider;
		String sql=String.format("select * from order_lines where order_no=\'%1$s\' and ORDERLINESTATUS!=\'1\'", OrderNo);
		try {
			cursor=provider.Query(sql);
			while (cursor.moveToNext()) {
				OrderLine line=new OrderLine();
				line.ID=cursor.getString(cursor.getColumnIndex("ID"));
				line.ORDER_NO=cursor.getString(cursor.getColumnIndex("ORDER_NO"));
				line.PRODUCT_ID=cursor.getString(cursor.getColumnIndex("PRODUCT_ID"));
				line.UOM_CODE=cursor.getString(cursor.getColumnIndex("UOM_CODE"));
				line.QUANTITY_ORDERED=cursor.getInt(cursor.getColumnIndex("QUANTITY_ORDERED"));
				line.LINE_AMOUNT=cursor.getFloat(cursor.getColumnIndex("LINE_AMOUNT"));
				line.Quantity_Received=cursor.getString(cursor.getColumnIndex("Quantity_Received"));
				line.ARRIVAL_date=cursor.getString(cursor.getColumnIndex("ARRIVAL_date"));
				line.Confirmed_Date=cursor.getString(cursor.getColumnIndex("Confirmed_Date"));
				line.OrderLineStatus=cursor.getString(cursor.getColumnIndex("OrderLineStatus"));
				line.promotion_id=cursor.getString(cursor.getColumnIndex("promotion_id"));
				line.CANCELLED=cursor.getString(cursor.getColumnIndex("CANCELLED"));
				list.add(line);

			}
		} catch (Exception err) {

			err.printStackTrace();
			MobclickAgent.reportError(context, err.getMessage());

		}finally{
			if(cursor!=null){
				cursor.close();
				cursor=null;
			}
		}
		return list;
	}
	
	private String _ErrorMessage;
	
	public String getErrorMessage()
	{
		 String str =_ErrorMessage;
		 _ErrorMessage = "";
		 return str;
	}

	public boolean PrintOrder(Context context, OrderEntity entity,String Tips)
	{
		//拼接订单格式,采用JSON格式
		JSONObject  object = new JSONObject();
		try {
			object.put("ORDER_NO", entity.ORDER_NO);
			object.put("ORDER_DATE", entity.ORDER_DATE);
			object.put("ORDERTYPE", entity.ORDERTYPE);

			object.put("DELIVERY_TYPE", entity.DELIVERY_TYPE);
			object.put("TOTAL_QUANTITY", entity.TOTAL_QUANTITY);
			object.put("ADDITIONAL_INFO", entity.ADDITIONAL_INFO);
			object.put("CONTACT_LINK", entity.CONTACT_LINK);
			object.put("CONTACT_MAN", entity.CONTACT_MAN);
			object.put("DELIVERY_ADDRESS", entity.DELIVERY_ADDRESS);
			object.put("DISC_AMOUNT", entity.DISC_AMOUNT);
			object.put("DISC_RATE", entity.DISC_RATE);
			object.put("REQ_DELIVERY_DATE", entity.REQ_DELIVERY_DATE);
			object.put("STATUS", entity.STATUS);
			object.put("TOTAL_AMOUNT", entity.TOTAL_AMOUNT);
			object.put("DELIVERY_TYPE", entity.DELIVERY_TYPE);
			object.put("CONFIRMED_DATE", entity.CONFIRMED_DATE);
			object.put("EXTENDED_AMOUNT", entity.EXTENDED_AMOUNT);
			object.put("TRUCK_CODE", entity.TRUCK_CODE);
			//插入订单行
			JSONArray array = new JSONArray();
			for(OrderLine line : entity.Lines)
			{
				JSONObject  obj = new JSONObject();
				obj.put("PRICE", line.LINE_AMOUNT/line.QUANTITY_ORDERED);
				obj.put("QUANTITY_ORDERED", line.QUANTITY_ORDERED);
				obj.put("DESCRIPTION", line.Product.DESCRIPTION);
				obj.put("CODE", line.Product.CODE);
				obj.put("OrderLineStatus", line.OrderLineStatus);
				array.put(obj);
			}
			object.put("LINES", array);
			//插入支付详情


		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			this._ErrorMessage = e.getMessage();
			return false;
		}

		boolean success=false;
		try
		{
			int timeoutConnection = 3000;   
			int timeoutSocket = 5000;   
			BasicHttpParams httpParameters = new BasicHttpParams();// Set the timeout in milliseconds until a connection is established.   
			HttpConnectionParams.setConnectionTimeout(httpParameters, timeoutConnection);// Set the default socket timeout (SO_TIMEOUT) // in milliseconds which is the timeout for waiting for data.   
			HttpConnectionParams.setSoTimeout(httpParameters, timeoutSocket);   
			//提交请求
			HttpClient client = new DefaultHttpClient(httpParameters);   



			//设置请求的地址
			SharedPreferences preferences = context.getSharedPreferences("PRINT", Context.MODE_PRIVATE);
			String address = preferences.getString("ADDRESS", "http://192.168.1.10:8080/");
			HttpPost post = new HttpPost(address + "/print.ashx?" + entity.ORDER_NO);
			post.setEntity(new ByteArrayEntity(object.toString().getBytes()));
			// 发送请求并获取反馈
			HttpResponse response = client.execute(post);
			post = null;
			object = null;
			System.gc();
			// 判断请求是否成功处理
			if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) 
			{

				String result = EntityUtils.toString(response.getEntity(), "UTF-8");
				if("OK".equals(result))
					success= true;
				else
				{
					_ErrorMessage = result;
				}
			}

		}
		catch(Exception err)
		{
			err.printStackTrace();
			this._ErrorMessage = "打印服务访问失败";
		}
		return success;
	}


	public List<PaymentEntity> getAllPaymentByOrderId(Context context,String orderId){
		List<PaymentEntity> list=new ArrayList<PaymentEntity>();
		SQLiteCursor cursor=null;
		String sql ="select * from PAYMENT_RECORD where ORDER_ID=\'%1$s\' AND ACTIVE=\'True\' ";
		try {
			sql=String.format(sql, orderId);
			cursor=MyApplication.getInstance().DataProvider.Query(sql);
			while (cursor.moveToNext()) {
				PaymentEntity entity=new PaymentEntity();
				entity.ID=cursor.getString(cursor.getColumnIndex("ID"));
				entity.ORDER_ID=cursor.getString(cursor.getColumnIndex("ORDER_ID"));
				entity.CUSTOMER_ID=cursor.getString(cursor.getColumnIndex("CUSTOMER_ID"));
				entity.USER_ID=cursor.getString(cursor.getColumnIndex("USER_ID"));
				entity.PAYMENT_AMOUNT=cursor.getString(cursor.getColumnIndex("PAYMENT_AMOUNT"));
				entity.PAYMENT_TYPE=cursor.getInt(cursor.getColumnIndex("PAYMENT_TYPE"));
				entity.PAYMENT_DATE=cursor.getString(cursor.getColumnIndex("PAYMENT_DATE"));
				entity.ACTIVE=cursor.getString(cursor.getColumnIndex("ACTIVE"));
				list.add(entity);
			}
		} catch (Exception err) {
			err.printStackTrace();
			MobclickAgent.reportError(context, err.getMessage());
		}finally{
			if(cursor!=null){
				cursor.close();
				cursor=null;
			}
		}
		return list;
	}




}
